<!--菜单管理-->
<template>
  <div id="menu" class="app-container">
    <!--列表-->
    <div class="filter-container color-danger" style="font-size:12px;padding-bottom:10px">
      说明&nbsp;&nbsp;排列顺序不影响系统菜单的显示顺序
    </div>
    <div class="conmmon-container-main flex-row">
      <div class="flex-main" style="flex:1;background:#fff">
        <div class="table-container flex-main">
          <div class="table-container-header">
            <table-toolbar :remove="false" @create="handleCreate" @refresh="handleFilter">
              <template>
                <el-button type="primary" icon="el-icon-download" plain @click="handleDownloadPermissionCode">下载权限编码</el-button>
              </template>
              <template slot="rightTool">
                <search v-model="listQuery.menuName" placeholder="请输入菜单名称" @search="handleFilter" />
                <el-tooltip class="item" effect="dark" :content="expandAll?'收缩':'展开'" placement="top">
                  <el-button circle :icon="expandAll?'el-icon-arrow-up':'el-icon-arrow-down'" @click="expandAll?handleMerge():handleExpand()" />
                </el-tooltip>
              </template>
            </table-toolbar>
          </div>
          <el-table
            v-if="multipleTable"
            ref="multipleTable"
            :data="menuData"
            :tree-props="{children: 'permissionVos', hasChildren: 'hasChildren'}"
            header-cell-class-name="table-header"
            fit
            highlight-current-row
            row-key="id"
            height="100%"
            :default-expand-all="expandAll"
            @selection-change="handleSelectionChange"
            @row-click="handleRowClick"
            @sort-change="sortChange">
            <el-table-column :show-overflow-tooltip="true" label="菜单名称" prop="name" sortable width="200" />
            <el-table-column label="类型" prop="type" width="80" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.type===1" class="color-primary">菜单</span>
                <span v-if="scope.row.type===2" class="color-danger">按钮</span>
              </template>
            </el-table-column>
            <el-table-column label="图标" prop="icon" width="100" align="center">
              <template slot-scope="scope">
                <template v-if="scope.row.icon">
                  <span v-if="scope.row.icon.indexOf('icon-')>-1" class="icon iconfont" :class="scope.row.icon" />
                  <svg-icon v-else :icon-class="scope.row.icon" style="font-size:26px" class="icon" />
                </template>
              </template>
            </el-table-column>
            <el-table-column label="权限标识" prop="permissionValue" min-width="200" show-overflow-tooltip />
            <el-table-column label="排序" prop="orders" width="100" align="center" />
            <el-table-column label="添加应用" prop="application" width="80" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.application===0">否</span>
                <span v-if="scope.row.application===1" class="color-primary">是</span>
              </template>
            </el-table-column>
            <el-table-column label="是否启用" prop="isDisabled" width="100" align="center">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.isDisabled"
                  @change="changeIsState(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column prop="gmtModified" sortable label="操作时间" width="160">
              <template slot-scope="scope">{{ scope.row.gmtModified | formatDate }}</template>
            </el-table-column>
            <el-table-column label="操作" align="center" fixed="right" width="120">
              <template slot-scope="scope">
                <button-option icon="iconNextLevel" icon-type="svg" skin="primary" title="新增下级" @click="handleCreateNext(scope.row)" />
                <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleUpdate(scope.row)" />
                <button-option icon="el-icon-delete" skin="danger" title="删除" @click="handleRemoveSingle(scope.row)" />
                <button-option icon="iconPermission" icon-type="svg" skin="primary" title="按钮权限" @click="handleDistributionPermission(scope.row)" />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="menu-right">
        <div class="common-title" style="margin:0 10px 10px"><h2>新增/编辑菜单</h2></div>
        <el-form ref="dataForm" :rules="recordForm.rules" :model="recordForm.menuRecord" label-position="right" label-width="120px">

          <el-form-item label="所属上级:" prop="pid">
            <el-select-tree v-model="recordForm.menuRecord.pid" :data="menuDataTemp" :props="{children: 'permissionVos', label: 'name'}" />
          </el-form-item>
          <el-form-item label="编码:" prop="menuCode">
            <el-input v-model="recordForm.menuRecord.menuCode" maxlength="30" show-word-limit placeholder="请输入菜单编码" @input="updateView($event)" />
          </el-form-item>
          <el-form-item label="名称:" prop="name">
            <el-input v-model="recordForm.menuRecord.name" maxlength="20" show-word-limit placeholder="请输入菜单名称" />
          </el-form-item>
          <el-form-item label="图标:" prop="icon">
            <icon-select v-model="recordForm.menuRecord.icon" placeholder="请选择菜单图标" />
          </el-form-item>
          <el-form-item label="排序:" prop="orders">
            <el-input-number v-model="recordForm.menuRecord.orders" placeholder="请输入排序" show-word-limit style="width:100%" />
          </el-form-item>
          <el-form-item label="添加到应用:" prop="application">
            <el-radio v-model="recordForm.menuRecord.application" :label="0">否</el-radio>
            <el-radio v-model="recordForm.menuRecord.application" :label="1">是</el-radio>
          </el-form-item>
          <el-form-item v-if="recordForm.menuRecord.application===1" label="所属应用:" prop="applicationGroup">
            <data-dict-select v-model="recordForm.menuRecord.applicationGroup" :code="'applicationGroup'" placeholder="请选择所属应用" />
          </el-form-item>
          <el-form-item>
            <el-button style="width:100%" :loading="recordForm.buttonLoading" type="primary" @click="recordForm.status === 'create'?createData():updateData()">操作</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!--新增/编辑对话框-->
    <side-box :show="permissionSideBox.show" :title="permissionSideBox.title" width="700px" @close="permissionSideBox.show =!permissionSideBox.show">
      <template slot="body">
        <div class="table-container flex-main">
          <div class="table-container-header" style="padding-top: 0px;">
            <el-row :gutter="10">
              <el-col :span="3">
                <el-button type="primary" icon="el-icon-plus" plain @click="handleCreatePermission">新增</el-button>
              </el-col>
              <el-col :span="5">
                <el-dropdown @command="handleCommand">
                  <span class="el-dropdown-link">
                    <el-button type="text" icon="el-icon-plus">常用按钮权限</el-button><i class="el-icon-arrow-down el-icon--right" />
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="save">新增</el-dropdown-item>
                    <el-dropdown-item command="update">编辑</el-dropdown-item>
                    <el-dropdown-item command="details">详情</el-dropdown-item>
                    <el-dropdown-item command="remove">删除</el-dropdown-item>
                    <el-dropdown-item command="removeAll">批量删除</el-dropdown-item>
                    <el-dropdown-item command="import">导入</el-dropdown-item>
                    <el-dropdown-item command="export">导出</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-col>
            </el-row>
          </div>
          <el-table
            ref="multipleTable"
            :data="permissionList"
            header-cell-class-name="table-header"
            fit
            height="100%"
            highlight-current-row
            stripe
            @selection-change="handleSelectionChange"
            @row-click="handleRowClick"
            @sort-change="sortChange">
            <el-table-column align="center" prop="id" label="#" width="60">
              <template slot-scope="scope">{{ scope.$index+1 }}</template>
            </el-table-column>
            <el-table-column label="排序" prop="orders" width="100" align="center" />
            <el-table-column label="权限值" :show-overflow-tooltip="true" prop="permissionValue" min-width="200">
              <template slot-scope="scope">
                {{ scope.row.name }}
                <span class="color-primary" style="margin-left: 8px;"><copy-text :content="scope.row.permissionValue" /></span>
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center" fixed="right" width="90">
              <template slot-scope="scope">
                <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleEdit(scope.row)" />
                <button-option icon="el-icon-delete" skin="danger" title="删除" @click="removePermission(scope.row)" />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
    </side-box>
    <model-dialog
      :title="permissionDialogTitle"
      :visible.sync="permissionDialogVisible"
      width="600px"
      @close="permissionDialogVisible=!permissionDialogVisible">
      <div>
        <el-form ref="dataForm" :rules="permissionRecordForm.rules" :model="permissionRecordForm.permissionRecord" label-position="right" label-width="120px">
          <el-form-item label="所属菜单:">
            <el-input v-model="permissionRecordForm.permissionRecord.menuName" disabled maxlength="20" show-word-limit placeholder="请输入权限名称" />
          </el-form-item>
          <el-form-item label="权限名称:" prop="name">
            <el-input v-model="permissionRecordForm.permissionRecord.name" maxlength="30" show-word-limit placeholder="请输入权限名称" />
          </el-form-item>
          <el-form-item label="权限值:" prop="permissionValue">
            <el-input v-model="permissionRecordForm.permissionRecord.permissionValue" maxlength="50" show-word-limit placeholder="请输入权限值" />
          </el-form-item>
          <el-form-item label="排序:" prop="orders">
            <el-input-number v-model="permissionRecordForm.permissionRecord.orders" placeholder="请输入排序" show-word-limit style="width:100%" />
          </el-form-item>
        </el-form>
      </div>
      <template slot="footer">
        <el-button type="primary" @click=" permissionRecordForm.permissionRecord.statusRole==='create'?submitPermission():updatePermission()">确 定</el-button>
      </template>
    </model-dialog>
  </div>
</template>
<script>
export default {
  components: { },

  data() {
    return {

      total: 0,
      menuList: [],
      expandAll: false,
      multipleTable: true,
      menuData: [],
      menuDataTemp: [],
      multipleSelectionRecords: [],
      listQuery: {
        menuName: '',
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        sort: '+orders'
      },
      defaultTreeProps: {
        children: 'permissionVos',
        label: 'name',
        isLeaf: 'leaf'
      },
      recordForm: {
        status: 'create', // 对话框状态
        buttonLoading: false,
        pidMenuName: '',
        menuRecord: {
          menuCode: '',
          name: '',
          icon: '',
          pid: '',
          orders: ''
        },
        rules: {
          menuCode: [
            { required: true, message: '请输入菜单编码', trigger: 'blur' }
          ],
          name: [
            { required: true, message: '请输入菜单名称', trigger: 'blur' }
          ],
          icon: [
            { required: true, message: '请选择图标', trigger: 'blur' }
          ],
          pid: [
            { required: true, message: '请选择所属上级', trigger: 'blur' }
          ],
          applicationGroup: [
            { required: true, message: '请选择所属应用', trigger: 'blur' }
          ],
          orders: [
            { required: true, message: '请输入排序', trigger: 'blur' }
          ]
        }
      },
      permissionSideBox: {
        show: false,
        title: '按钮权限',
        buttonLoading: false,
        status: 'create'
      },
      permissionList: [],
      selectedMenu: {},
      permissionRecordForm: {
        pidMenuName: '',
        permissionRecord: {
          statusRole: 'create',
          permissionValue: '',
          name: '',
          pid: ''
        },
        rules: {
          permissionValue: [
            { required: true, message: '请输入权限值', trigger: 'blur' }
          ],
          name: [
            { required: true, message: '请输入权限名称', trigger: 'blur' }
          ],
          pid: [
            { required: true, message: '请选择所属菜单', trigger: 'blur' }
          ]
        }
      },
      permissionDialogVisible: false,
      permissionDialogTitle: '新增按钮权限'
    }
  },
  created() {
    this.resetMenuRecord()
    this.handleFilter()
    // this.fetchPermissionListData()
  },
  methods: {
    handleMerge() {
      this.multipleTable = false
      this.expandAll = false
      this.$nextTick(() => {
        this.multipleTable = true
      })
    },
    handleExpand() {
      this.multipleTable = false
      this.expandAll = true
      this.$nextTick(() => {
        this.multipleTable = true
      })
    },
    /**
     * 全选/反选
     */
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },
    /**
     * 单击一行
     */
    handleRowClick(row) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    handleTabsClick() {
      this.handleFilter()
      this.resetMenuRecord()
    },

    // 选择树节点事件
    handleCheckChange(item, check, children) {
      if (check === true) {
        this.$refs.tree.setCheckedKeys([])
        this.$refs.tree.setCheckedKeys([item.id])
        this.recordForm.pidMenuName = item.name
        this.recordForm.menuRecord.pid = item.id
      }
    },

    // 获取列表数据
    async fetchData() {
      const response = await this.$store.dispatch('permissionTreeTable', this.listQuery)
      this.menuData = response
      this.assembleData(this.menuData)
      this.menuDataTemp = [{ name: '根目录', id: '0' }, ... this.menuData]
    },
    assembleData(items) {
      items.filter((item) => {
        item.isDisabled = !item.isDisabled
        if (item.permissionVos) {
          item.upmsPermissions = this.assembleData(item.permissionVos)
        }
        return true
      })
      return items
    },
    // 排序
    sortChange(data) {
      const { prop, order } = data
      if (prop) {
        if (order === 'ascending') {
          this.listQuery.sort = '+' + prop
        } else {
          this.listQuery.sort = '-' + prop
        }
      } else {
        this.listQuery.sort = '+orders'
      }
      this.handleFilter()
    },
    // 搜索
    handleFilter() {
      this.fetchData()
    },
    // 刷新
    handleReset() {
      this.listQuery = {
        menuName: '',
        sort: '+orders'
      }
      this.fetchData()
    },
    // 新增
    handleCreate() {
      this.recordForm.menuRecord = {
        pid: '0',
        pName: '根目录',
        orders: 0,
        application: 0
      }
      this.recordForm.status = 'create'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 新增
    handleCreateNext(row) {
      this.recordForm.menuRecord = {
        pid: row.id,
        pName: row.name,
        orders: 0,
        application: 0
      }
      this.recordForm.status = 'create'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 确定按钮
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.recordForm.buttonLoading = true
          this.$store.dispatch('menuSave', this.recordForm.menuRecord).then(response => {
            this.recordForm.buttonLoading = false
            this.msgSuccess('添加成功')
            this.handleReset()
            this.resetMenuRecord()
          }).catch(() => {
            this.recordForm.buttonLoading = false
          })
        }
      })
    },
    // 编辑
    async handleUpdate(row) {
      this.recordForm.status = 'update'
      this.recordForm.menuRecord = Object.assign({}, row)
      this.recordForm.menuRecord.menuCode = row.permissionValue
      if (row.pid === '0') {
        this.recordForm.menuRecord = {
          ...this.recordForm.menuRecord,
          pName: '根目录'
        }
      } else {
        var res = await this.$store.dispatch('upmsPermissionsGetById', row.pid)
        this.recordForm.menuRecord = {
          ...this.recordForm.menuRecord,
          pName: res.name
        }
      }
      console.log(this.recordForm.menuRecord)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          delete this.recordForm.menuRecord.permissionVos
          delete this.recordForm.menuRecord.upmsPermissions
          const tempData = Object.assign({}, this.recordForm.menuRecord)
          this.recordForm.buttonLoading = true
          this.$store.dispatch('menuUpdate', tempData).then(response => {
            this.recordForm.buttonLoading = false
            this.msgSuccess('编辑成功')
            this.handleFilter()
            this.resetMenuRecord()
          }).catch(() => {
            this.recordForm.buttonLoading = false
          })
        }
      })
    },
    // 单个删除
    handleRemoveSingle(row) {
      this.multipleSelectionRecords = []
      this.multipleSelectionRecords.push(row)
      this.$refs.multipleTable.clearSelection()
      this.$refs.multipleTable.toggleRowSelection(row, true)
      this.removeRecord()
    },
    // 批量删除
    removeRecord() {
      if (this.multipleSelectionRecords.length > 0) {
        const ids = []
        this.multipleSelectionRecords.forEach(function(v, i) {
          ids.push(v.id)
        })
        this.$confirm('此操作将永久删除记录, 是否继续?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('permissionRemove', ids).then(response => {
            this.handleReset()
            this.msgSuccess('删除成功!')
          }).catch(() => {})
        }).catch(() => { })
      } else {
        this.msgWarning('请选择要删除的记录')
      }
    },

    changeIsState(row) {
      var temp = Object.assign({}, row) // copy obj
      this.$confirm('您确定' + (temp.isDisabled === false ? '禁用' : '启用') + '菜单[' + temp.name + '], 是否继续?', '提示', {
        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
        .then(() => {
          const params = {
            id: temp.id,
            isDisabled: !temp.isDisabled
          }
          this.$store.dispatch('changePermissionState', params).then(response => {
            this.msgSuccess('修改成功')
            this.handleFilter()
          }).catch(() => {})
        }).catch(() => {
          row.isDisabled = !row.isDisabled
        })
    },
    updateView(e) {
      this.$forceUpdate()
    },
    // 重置实体
    resetMenuRecord() {
      this.recordForm.menuRecord = {
        pid: '0',
        pName: '根目录',
        icon: '-'
      }
      // this.$refs.tree.setCheckedKeys([])
    },

    // 权限开始
    async fetchPermissionListData() {
      const response = await this.$store.dispatch('listPermission', { type: 2, pid: this.selectedMenu.id })
      this.listLoading = false
      this.permissionList = response
    },
    handleDistributionPermission(row) {
      this.permissionSideBox.show = true
      this.permissionSideBox.title = '按钮权限-' + row.name
      this.selectedMenu = row
      this.fetchPermissionListData()
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    handleCommand(command) {
      this.$store.dispatch('fastCreatePermission', { permissionValue: command, pid: this.selectedMenu.id }).then(response => {
        this.msgSuccess('添加成功')
        this.fetchPermissionListData()
      }).catch(() => {
      })
    },
    // 新增按钮
    handleCreatePermission() {
      this.permissionDialogVisible = true
      this.permissionRecordForm.permissionRecord = {}
      this.permissionRecordForm.permissionRecord.statusRole = 'create'
      this.permissionRecordForm.permissionRecord.menuName = this.selectedMenu.name
      this.permissionRecordForm.permissionRecord.pid = this.selectedMenu.id
      this.permissionRecordForm.permissionRecord.orders = 0
    },
    // 保存权限
    submitPermission() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.permissionDialogVisible = false
          this.$store.dispatch('permissionSave', this.permissionRecordForm.permissionRecord).then(response => {
            this.msgSuccess('添加成功')
            this.fetchPermissionListData()
            this.resetMenuRecord()
            this.permissionDialogVisible = false
          }).catch(() => {
            this.permissionDialogVisible = true
          })
        }
      })
    },
    // 编辑
    handleEdit(row) {
      this.permissionRecordForm.permissionRecord = Object.assign({}, row)
      this.permissionRecordForm.permissionRecord.menuName = this.selectedMenu.name

      this.permissionDialogVisible = true
      this.permissionRecordForm.permissionRecord.statusRole = 'update'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 编辑保存按钮
    updatePermission() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.permissionRecordForm.permissionRecord)
          this.$store.dispatch('permissionUpdate', tempData).then(response => {
            this.msgSuccess('修改成功')
            this.fetchPermissionListData()
            this.permissionDialogVisible = false
          }).catch(() => {
            this.permissionDialogVisible = true
          })
        }
      })
    },
    // 删除
    removePermission(row) {
      this.multipleSelectionRecords = []
      this.multipleSelectionRecords.push(row)
      this.handleRemovePermission()
    },
    handleRemovePermission() {
      const ids = []
      this.multipleSelectionRecords.forEach(function(v, i) {
        ids.push(v.id)
      })
      this.$confirm('此操作将永久删除记录, 是否继续?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('permissionRemove', ids).then(response => {
          this.fetchPermissionListData()
          this.msgSuccess('删除成功!')
        }).catch(() => {})
      }).catch(() => { })
    },
    handleDownloadPermissionCode() {
      this.$store.dispatch('downloadPermissionCode').then(response => {
        var title = `权限编码_${this.T.formatDate(new Date().getTime(), this.T.DATE_TIME_FMT1)}`
        if ('msSaveOrOpenBlob' in navigator) { // 兼容ie
          const blob = new Blob([response])
          window.navigator.msSaveOrOpenBlob(blob, title + '.js')
          return
        } else {
          const link = document.createElement('a')
          const blob = new Blob([response])
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          link.setAttribute('download', decodeURI(title) + '.js')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        }
      }).catch((e) => {
        console.log(e)
      })
    }

  }
}
</script>

<style lang="scss">
  #menu{
    .el-tabs__content{
      height: 0px !important;
      padding: 0px !important;
    }
    .el-tabs--border-card{
      border: 0px;
    }
    .menu-right{
      width:400px;
      height: 100%;
      margin-left: 10px;
      padding-right: 10px;
      background: #fff;
    }
  }
</style>
